﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.ServiceModel;
using System.Configuration;
using XenAppServices.ServiceLibrary.XenApp6;

namespace XenAppServices.ServiceHost.XenApp6
{
    partial class XAServicesServiceHost : ServiceBase
    {
        private bool loggingEnabled;
        private string logName;
        private string logSource;

        private System.ServiceModel.ServiceHost host = new System.ServiceModel.ServiceHost(typeof(XAServicesService));

        public XAServicesServiceHost()
        {
            InitializeComponent();

            this.loggingEnabled = false;
            this.logSource = "XenApp Services";
            this.logName = ConfigurationManager.AppSettings["LogName"];

            if (ConfigurationManager.AppSettings["LoggingEnabled"].ToUpper() == "TRUE")
            {
                this.loggingEnabled = true;
            }

            if (this.loggingEnabled)
            {
                if (!EventLog.SourceExists(this.logSource))
                {
                    EventLog.CreateEventSource(this.logSource, this.logName);
                }
            }
        }

        protected override void OnStart(string[] args)
        {
            this.Log("Starting " + this.ServiceName);

            try
            {
                host.Open();
            }
            catch (Exception ex)
            {
                Log(ex);
            }
        }

        protected override void OnStop()
        {
            if (host != null)
            {
                host.Close();
            }

            Log(this.ServiceName + " Stopped");
        }

        #region EvenLogging

        private void Log(string message, EventLogEntryType type)
        {
            if (this.loggingEnabled)
            {
                EventLog.WriteEntry(message, type);
            }
        }

        private void Log(string message)
        {
            Log(message, EventLogEntryType.Information);
        }

        private void Log(Exception ex)
        {
            Log(ex.Message + "\n" + ex.StackTrace, EventLogEntryType.Error);
        }

        #endregion
    }
}
